package com.youxue.teachin.webplugin;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewFragment;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.hybrid.utils.NetworkUtils;
import com.hybrid.utils.UriParams;
import com.hybrid.webview.MenuItem;
import com.hybrid.webview.ParamBuilder;
import com.hybrid.webview.WVWebView;
import com.hybrid.webview.WVWebView.Callback;
import com.library.uiframework.fragment.ActionBarLayoutFragment;
import com.library.uiframework.fragment.ptr.PtrViewHelper;
import com.library.uiframework.slidingclose.SlidingClosableRelativeLayout;
import com.library.uiframework.utils.ListUtils;
import com.library.uiframework.utils.Log;
import com.library.uiframework.utils.SDKVersionUtils;
import com.library.uiframework.utils.StringUtils;
import com.library.uiframework.widget.actionbar.ActionBarLayout;
import com.library.uiframework.widget.actionbar.ActionBarLayout.Action;
import com.library.uiframework.widget.actionbar.ActionBarLayout.OnActionClickListener;
import com.library.uiframework.widget.actionbar.ActionMenuItem;
import com.youxue.teachin.R;
import com.youxue.teachin.common.utils.SchemaParam;
import com.youxue.teachin.webplugin.JavaScriptObject.JavaScriptListener;
import com.youxue.teachin.webplugin.WebViewParam.LoadingMode;
import com.youxue.teachin.youmen.UMenUtils;
import com.youxue.teachin.youmen.UmenEventId;
import com.youxue.teachin.youmen.UmenEventId.EventMap;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout.Mode;
import in.srain.cube.views.ptr.PtrHandler;
import org.json.JSONException;
import org.json.JSONObject;

import static android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
import static com.library.uiframework.fragment.ptr.PtrViewHelper.OnPtrHandlerListener;
import static com.youxue.teachin.common.utils.SchemaParam.PARAM_WEBVIEW;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-10 21:08
 * @version: 9.1.0
 */
public class WebFragment extends ActionBarLayoutFragment implements OnPtrHandlerListener, JavaScriptListener {
    private static final String TAG = "WebFragment";

    private static final int ACTION_LEFT_ID = 1001;
    private static final int ACTION_RIGHT_ID = 1002;
    private static final int ACTION_CLOSE_ID = 1003;
    private static final int ACTION_REFRESH_ID = 1004;
    private static final String ORIGIN_DEFAULT_TITLE = "";
    private static final int HORIZONTAL_LOADING_HIDE_DELAY = 500;

    private WVWebView mWebView;
    private PtrClassicFrameLayout mPtrFrameLayout;
    private WebViewParam mWebViewParam = new WebViewParam();

    private View.OnTouchListener mWebViewOnTouchListener;

    private ProgressBar mPbCircle;
    private ProgressBar mPbHorizontal;
    private View mLoadFailedView;
    private WebViewParam.LoadingMode mLoadingMode = LoadingMode.HORIZONTAL;

    private List<ActionMenuItem> mMenuItemList = new ArrayList<ActionMenuItem>();
    private Map<ActionMenuItem, MenuItem> mMenuItemMap = new LinkedHashMap<ActionMenuItem, MenuItem>();
    private List<Menu> mRightMenuList;

    private String mWebPageName;

    public static WebViewFragment newInstance(String url) {
        WebViewParam param = new WebViewParam(url);
        Bundle bundle = new Bundle();
        bundle.putSerializable(PARAM_WEBVIEW, param);
        WebViewFragment fragment = new WebViewFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public static WebViewFragment newInstance(WebViewParam param) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(PARAM_WEBVIEW, param);
        WebViewFragment fragment = new WebViewFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected boolean needBackAction() {
        return mWebViewParam.mNeedActionBack;
    }

    @Override
    protected boolean needMenuAction() {
        return mWebViewParam.mNeedMenu;
    }

    @Override
    protected View onCreateContentView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        initWebParamFromArguments();
        return layoutInflater.inflate(R.layout.web_layout_fragment, viewGroup, false);
    }

    @Override
    protected Action createBack() {
        return addLeftImageAction(ACTION_BACK, R.drawable.top_return);
    }

    @Override
    protected void onCreatePopupMenu(List<ActionMenuItem> menus) {
        super.onCreatePopupMenu(menus);
        menus.addAll(mMenuItemList);
    }

    private Menu getMenu(int menuId) {
        Menu retMenu = null;
        for (Menu menu : mRightMenuList) {
            if (menuId == menu.id) {
                retMenu = menu;
                break;
            }
        }
        return retMenu;
    }

    @Override
    protected void onActionClick(int actionId, Action action) {
        super.onActionClick(actionId, action);
        if (ListUtils.isNotEmpty(mMenuItemList)) {
            ParamBuilder paramBuilder = new ParamBuilder();
            JSONObject jsonObject = new JSONObject();
            Menu menu = getMenu(actionId);
            if (menu == null) {
                return;
            }
            try {
                int id = menu.id;
                String name = menu.name;
                jsonObject.put("id", id);
                jsonObject.put("name", null != name ? name : "");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            paramBuilder.addParamJsonObject("menu", jsonObject);
            android.util.Log.e("致伟",
                this.getClass().getSimpleName() + " onActionClick: =" + paramBuilder.buildParamString());

            fireEvent(MenuItem.EVENT_MENU_ITEM_CLICK_INVOKE, paramBuilder.buildParamString());
        }
    }

    @Override
    protected boolean onPopupMenuSelected(View view, ActionMenuItem actionMenuItemSelected, int position) {
        // 交予Plugin处理
        for (int index = 0; index < mMenuItemList.size(); index++) {
            ActionMenuItem actionMenuItem = mMenuItemList.get(index);
            if (actionMenuItem == actionMenuItemSelected) {
                MenuItem menuItem = mMenuItemMap.get(actionMenuItem);
                ParamBuilder paramBuilder = new ParamBuilder();
                JSONObject jsonObject = new JSONObject();
                try {
                    String id = menuItem.getId();
                    String name = menuItem.getName();
                    jsonObject.put("id", null != id ? id : "");
                    jsonObject.put("name", null != name ? name : "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                paramBuilder.addParamJsonObject("menu", jsonObject);
                fireEvent(MenuItem.EVENT_MENU_ITEM_CLICK_INVOKE, paramBuilder.buildParamString());
                return false;
            }
        }
        // 交予框架处理
        return super.onPopupMenuSelected(view, actionMenuItemSelected, position);
    }

    private void updateMenuInner(List<MenuItem> menuItemList) {
        mMenuItemList.clear();
        mMenuItemMap.clear();
        if (null != menuItemList) {
            for (int index = 0; index < menuItemList.size(); index++) {
                MenuItem menuItem = menuItemList.get(index);
                ActionMenuItem actionMenuItem = new ActionMenuItem(MenuItem.MENU_ITEM_ID_INDEX + index,
                    menuItem.getName());
                mMenuItemList.add(actionMenuItem);
                mMenuItemMap.put(actionMenuItem, menuItem);
            }
        }
    }

    private void initWebParamFromArguments() {
        Bundle arguments = getArguments();
        if (null != arguments) {
            Serializable serializableParam = arguments.getSerializable(PARAM_WEBVIEW);
            if (null == serializableParam) {
                mWebViewParam.mUrl = arguments.getString(SchemaParam.URL);
                if (StringUtils.isNotEmpty(mWebViewParam.mUrl)) {

                    //Uri webViewUri = Uri.parse(mWebViewParam.mUrl);
                    //mWebViewParam.mNeedRefresh = "1".equals(webViewUri.getQueryParameter(SchemaParam
                    // .H5_NEED_REFRESH));
                    //mWebViewParam.mNeedActionBack = "1".equals(
                    //    webViewUri.getQueryParameter(SchemaParam.H5_NEED_BACK));
                    //mWebViewParam.mHideActionBar = "1".equals(
                    //    webViewUri.getQueryParameter(SchemaParam.H5_IDE_ACTION_BAR));
                    //mWebViewParam.mTitle = webViewUri.getQueryParameter(SchemaParam.TITLE);
                    UriParams uriParams = UriParams.from(mWebViewParam.mUrl);
                    mWebViewParam.mNeedRefresh = uriParams.getBoolean(SchemaParam.H5_NEED_REFRESH, true);
                    mWebViewParam.mNeedActionBack = uriParams.getBoolean(SchemaParam.H5_NEED_BACK, true);
                    mWebViewParam.mNotificationPtrRefresh = uriParams.getBoolean(SchemaParam.H5_INFORM_REFRESH, true);
                    mWebViewParam.mHideActionBar = uriParams.getBoolean(SchemaParam.H5_IDE_ACTION_BAR, false);
                    mWebViewParam.mTitle = uriParams.getString(SchemaParam.TITLE, null);
                    if (StringUtils.isNotEmpty(mWebViewParam.mTitle)) {
                        mWebViewParam.mTitleLock = true;
                        updateTitle(mWebViewParam.mTitle);
                    }
                }
            } else {
                mWebViewParam = (WebViewParam)serializableParam;
            }

            // 移除Serializable参数,防止Activity在onStop之后对Bundle数据进行Restore进行writeObject,产生NotSerializableException
            arguments.remove(PARAM_WEBVIEW);
        }
        // 获取LoadingMode
        if (mWebViewParam.mLoadingMode != LoadingMode.NONE) {
            mLoadingMode = mWebViewParam.mLoadingMode;
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 设置侧滑退出方式
        //        setSlidingCloseMode(SlidingClosableRelativeLayout.SLIDING_CLOSE_MODE_HORIZONTAL_RIGHT);
        setSlidingCloseMode(SlidingClosableRelativeLayout.SLIDING_CLOSE_MODE_NONE);
        // 获取WebView
        mPtrFrameLayout = findViewById(R.id.ptr_frame_layout);

        mWebView = findViewById(R.id.web_webview);
        mWebView.addJavascriptInterface(new JavaScriptObject(mWebView, this), "WebViewFunc");
        mLoadFailedView = findViewById(R.id.loadingview_failed);
        mLoadFailedView.setVisibility(View.INVISIBLE);
        mPtrFrameLayout.disableWhenHorizontalMove(true);
        mPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return mWebViewParam.mNeedRefresh && mWebView.getScrollY() <= 0;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                beginRefresh2H5();
            }
        });

        mLoadFailedView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoadFailedView.setVisibility(View.INVISIBLE);

                reload();
            }
        });

        mPbCircle = findViewById(R.id.layout_progress_circle);
        mPbHorizontal = findViewById(R.id.layout_progress_horizontal);
        //mWebView.actionSetHostContainer(this);
        if (SDKVersionUtils.hasLollipop() && mWebView.getSettings() != null) {
            mWebView.getSettings().setMixedContentMode(MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //// 增加Title手势监听
        //final GestureDetector detector = new GestureDetector(new SimpleOnGestureListener() {
        //
        //    @Override
        //    public boolean onDoubleTap(MotionEvent e) {
        //        Log.v(TAG, "title onDoubleTap");
        //        fireEvent(PluginConstants.EVENT_DOUBLE_CLICK_TITLE_INVOKE);
        //        return super.onDoubleTap(e);
        //    }
        //});
        //getActionBarLayout().getTitleView().setOnTouchListener(new OnTouchListener() {
        //    @Override
        //    public boolean onTouch(View v, MotionEvent event) {
        //        int action = event.getAction();
        //        if (action == MotionEvent.ACTION_DOWN) {
        //            detector.onTouchEvent(event);
        //            return true;
        //        } else {
        //            return detector.onTouchEvent(event);
        //        }
        //    }
        //});

        // 设置WebView Callback
        mWebView.actionSetCallback(new Callback() {
            @Override
            public void onReceivedTitle(String title) {
                updateTitle(title);
                mWebPageName = "web_" + title;
            }

            @Override
            public void onPageStarted(String url) {
                beginLoading();

            }

            @Override
            public void onPageFinished(String url) {
                endLoading();
                mPtrFrameLayout.refreshComplete();
                UMenUtils.onEvent(UmenEventId.EVENT_WEB_OPEN,
                    new EventMap()
                        .add("name", mWebPageName)
                        .add("url", url)
                        .buile());
            }

            @Override
            public void onProgressChanged(int progress) {
                progressLoading(progress);
            }

            @Override
            public void onReceivedError(WebView view, String failingUrl) {
                UMenUtils.onEvent(UmenEventId.EVENT_WEB_OPEN_ERROR,
                    new EventMap()
                        .add("url", failingUrl)
                        .buile());
                android.util.Log.e("致伟",
                    this.getClass().getSimpleName() + " onReceivedError: failingUrl=" + failingUrl);
                TextView info = (TextView)mLoadFailedView.findViewById(R.id.textview_load_failed);
                info.setText(NetworkUtils.isNetworkAvailable(mLoadFailedView.getContext()) ? R.string.load_comment_fail
                    : R.string.load_failed_no_network);
                mLoadFailedView.setVisibility(View.VISIBLE);
            }
        });
        mWebView.setAdvancedCallback(new WVWebView.IWebAdvancedCallback() {
            @Override
            public void onPageClose() {
                exit();
            }

            @Override
            public void onUpdateMenu(List<MenuItem> menuItemList) {
                updateMenuInner(menuItemList);
            }

            @Override
            public void onUpdateTitle(String title) {
                updateTitleFromCallback(title);
            }

            @Override
            public void onUpdateStatusBarAlpha(float alpha) {
                updateStatusBarAlpha(alpha);
            }
        });
        //mWebView.setOnUserDeniedActionLoadUrlListener(new WebViewCore.OnUserDeniedActionLoadUrlListener() {
        //    @Override
        //    public void onUserDenied(String url) {
        //        //如果用户拒绝了初始url, 需要back以下,不然就是留了一个黑屏
        //        if (StringUtils.equal(mWebViewParam.mUrl, url)) {
        //            onBackPressed();
        //        }
        //    }
        //});

        // 关闭入口
        if (mWebViewParam.mNeedCloseEntrance) {
            Log.v(TAG, "WebViewFragment close entrance (param)");
            initCloseEntrance();
        }
        // 强制关闭下拉刷新功能
        mPtrFrameLayout.setMode(Mode.NONE);
        new PtrViewHelper(mPtrFrameLayout, this);
        if (mWebViewParam.mNeedRefresh) {
            mPtrFrameLayout.setMode(Mode.REFRESH);
        }

        // 设置左上角Action
        if (null != mWebViewParam.mActionLeft) {
            Action action = addLeftImageAction(ACTION_LEFT_ID, mWebViewParam.mActionLeft.mActionNameResId);
            action.setOnActionClickListener(new OnActionClickListener() {
                @Override
                public void onClick(int id, Action action) {
                    if (id == ACTION_LEFT_ID) {
                        if (null != mWebViewParam.mActionLeft.mActionCallBack) {
                            mWebViewParam.mActionLeft.mActionCallBack.onActionClick();
                        }
                    }
                }
            });
        }
        // 设置右上角Action
        if (null != mWebViewParam.mActionRight) {
            Action action = addImageAction(ACTION_RIGHT_ID, mWebViewParam.mActionRight.mActionNameResId);
            action.setOnActionClickListener(new OnActionClickListener() {
                @Override
                public void onClick(int id, Action action) {
                    if (id == ACTION_RIGHT_ID) {
                        if (null != mWebViewParam.mActionRight.mActionCallBack) {
                            mWebViewParam.mActionRight.mActionCallBack.onActionClick();
                        }
                    }
                }
            });
        }
        // 设置ActionBar可见性
        if (mWebViewParam.mHideActionBar) {
            ActionBarLayout actionBarLayout = getActionBarLayout();
            if (null != actionBarLayout) {
                actionBarLayout.setVisibility(View.GONE);
            }
        }
        // 设置WebView Touch监听
        mWebView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (null != mWebViewOnTouchListener) {
                    return mWebViewOnTouchListener.onTouch(view, motionEvent);
                }
                return false;
            }
        });
        // 清除缓存数据
        if (mWebViewParam.mClearCache) {
            Log.v(TAG, "WebViewFragment clear cache (param)");
            mWebView.clearCache(true);
        }
        // 清除历史记录
        if (mWebViewParam.mClearHistory) {
            Log.v(TAG, "WebViewFragment clear history (param)");
            mWebView.clearHistory();
        }
        // 加载Url
        mWebView.loadUrl(mWebViewParam.mUrl);

    }

    void beginRefresh2H5() {
        if (mWebViewParam.mNotificationPtrRefresh) {
            String beginRefreshing = "javascript:beginRefreshing()";
            mWebView.evaluateJavascript(beginRefreshing);
        } else {
            mWebView.refresh();
        }
    }

    private void updateStatusBarAlpha(float alpha) {
        setFloatingMode(true);
        getActionBarLayout().setFloatingModeAlpha(alpha);
    }

    @Override
    public void onPause() {
        Log.v(TAG, "WebViewFragment onPause");
        if (null != mWebView) {
            mWebView.onPause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        Log.v(TAG, "WebViewFragment onResume");
        if (null != mWebView) {
            mWebView.onResume();
        }
        super.onResume();
    }

    @Override
    public void onDestroy() {
        Log.v(TAG, "WebViewFragment onDestroy");
        if (null != mWebView) {
            mWebView.setVisibility(View.GONE);
            ViewGroup parent = (ViewGroup)mWebView.getParent();
            if (null != parent) {
                parent.removeView(mWebView);
            }
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        Log.v(TAG, "WebViewFragment onBackPressed");

        //告诉h5,back事件
        fireEvent("WebPlugin.onBackPressed");

        //延时做nativeBack,防止h5死掉的话,没法返回
        mBackPressHandler.sendEmptyMessageDelayed(MSG_DO_BACK_PRESSED, 100);
    }

    private void realDoBackPressed() {
        if (null != mWebView) {
            mWebView.tryGoBack(true);
        } else {
            super.onBackPressed();
        }
    }

    private static final int MSG_DO_BACK_PRESSED = 1;

    private Handler mBackPressHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == MSG_DO_BACK_PRESSED) {
                realDoBackPressed();
            }
        }
    };

    /********************************************************************************
     * 私有方法
     ********************************************************************************/

    private void updateTitle(String title) {
        // 设置固定标题
        if (null != mWebViewParam.mTitle && mWebViewParam.mTitleLock) {
            Log.v(TAG, "WebViewFragment updateTitle 固定设置 (title) = " + mWebViewParam.mTitle);
            setTitle(mWebViewParam.mTitle);
        }
        // 设置动态标题
        else {
            if (null != title) {
                Log.v(TAG, "WebViewFragment updateTitle 动态设置 (title) = " + title);
                setTitle(title);
            } else if (null != mWebViewParam.mTitle) {
                Log.v(TAG, "WebViewFragment updateTitle 用户默认 (title) = " + mWebViewParam.mTitle);
                setTitle(mWebViewParam.mTitle);
            } else {
                Log.v(TAG, "WebViewFragment updateTitle 原生默认 (title) = " + ORIGIN_DEFAULT_TITLE);
                setTitle(ORIGIN_DEFAULT_TITLE);
            }
        }
    }

    private void updateTitleFromCallback(String title) {
        Log.v(TAG, "WebViewFragment updateTitleFromCallback (title) = " + title);
        if (null != title) {
            setTitle(title);
        }
    }

    private void beginLoading() {
        if (mLoadingMode == WebViewParam.LoadingMode.CIRCLE) {
            mPbCircle.setVisibility(View.VISIBLE);
        } else if (mLoadingMode == WebViewParam.LoadingMode.HORIZONTAL) {
            mPbHorizontal.removeCallbacks(mRunnableHideHorizontalLoading);
            mPbHorizontal.setProgress(0);
            mPbHorizontal.setVisibility(View.VISIBLE);
        }
    }

    private void endLoading() {
        if (mLoadingMode == WebViewParam.LoadingMode.CIRCLE) {
            mPbCircle.setVisibility(View.GONE);
        } else if (mLoadingMode == WebViewParam.LoadingMode.HORIZONTAL) {
            mPbHorizontal.setProgress(mPbHorizontal.getMax());
            mPbHorizontal.removeCallbacks(mRunnableHideHorizontalLoading);
            mPbHorizontal.postDelayed(mRunnableHideHorizontalLoading, HORIZONTAL_LOADING_HIDE_DELAY);
        }
    }

    private void progressLoading(int progress) {
        if (mLoadingMode == WebViewParam.LoadingMode.CIRCLE) {
            if (progress >= 100) {
                mPbCircle.setVisibility(View.GONE);
            } else {
                mPbCircle.setVisibility(View.VISIBLE);
            }
        } else if (mLoadingMode == WebViewParam.LoadingMode.HORIZONTAL) {
            if (progress >= 100) {
                mPbHorizontal.setProgress(mPbHorizontal.getMax());
                mPbHorizontal.removeCallbacks(mRunnableHideHorizontalLoading);
                mPbHorizontal.postDelayed(mRunnableHideHorizontalLoading, HORIZONTAL_LOADING_HIDE_DELAY);
            } else {
                mPbHorizontal.setProgress(progress);
                mPbHorizontal.setVisibility(View.VISIBLE);
            }
        }
    }

    private Runnable mRunnableHideHorizontalLoading = new Runnable() {
        @Override
        public void run() {
            mPbHorizontal.setVisibility(View.GONE);
        }
    };

    private void initCloseEntrance() {
        ActionBarLayout.Action action = addLeftImageAction(ACTION_CLOSE_ID, R.drawable.top_return);
        action.setOnActionClickListener(new ActionBarLayout.OnActionClickListener() {
            @Override
            public void onClick(int id, ActionBarLayout.Action action) {
                exit();
            }
        });
    }

    /********************************************************************************
     * 公开方法
     ********************************************************************************/

    public String getCurrentUrl() {
        if (null != mWebView) {
            return mWebView.getUrl();
        }
        return null;
    }

    public void load(String url) {
        if (null != mWebView) {
            mWebView.loadUrl(url);
        }
    }

    public void reload() {
        if (null != mWebView) {
            mWebView.refresh();
        }
    }

    public void fireEvent(String event) {
        fireEvent(event, null);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mWebView.onActivityResult(requestCode, resultCode, data);
    }

    public void fireEvent(String event, String data) {
        if (null != mWebView && null != event) {
            Log.v(TAG, "fireEvent event,data = " + event + "," + data);
            if (null != data) {
                mWebView.fireEvent(event, data);
            } else {
                mWebView.fireEvent(event);
            }
        }
    }

    public void exit() {
        finish();
    }

    public void updateMenu(List<MenuItem> menuItemList) {
        updateMenuInner(menuItemList);
    }

    public void addWebViewTouchListener(View.OnTouchListener listener) {
        mWebViewOnTouchListener = listener;
    }

    public void removeWebViewTouchListener() {
        mWebViewOnTouchListener = null;
    }

    @Override
    public void onLoadMoreBegin(PtrFrameLayout frameLayout) {

    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frameLayout) {
        //mWebView.refresh();
        beginRefresh2H5();
    }

    @Override
    public boolean onInterceptLoadMore() {
        return true;
    }

    @Override
    public boolean onInterceptRefresh() {
        if (!mWebViewParam.mNeedRefresh) {
            return true;
        }
        return mWebViewParam.mNeedRefresh && !(mWebView.getScrollY() == 0);
    }

    @Override
    public void endRefreshing() {
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.stopLoading();
                mPtrFrameLayout.refreshComplete();
            }
        });
    }

    @Override
    public void beginRefreshing() {
        // h5调用刷星，从新load
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mPtrFrameLayout.autoRefresh();
                mWebView.refresh();
            }
        });

    }

    @Override
    public void updateMenu(final String string) {
        if (StringUtils.isEmpty(string)) {
            return;
        }
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();
                    Menus menus = gson.fromJson(string, Menus.class);
                    if (ListUtils.isEmpty(menus.rightMenus)) {
                        return;
                    }
                    int maxRightMenus = Menus.MAX_MENUS;
                    List<Menu> menuList = ListUtils.removeItem(menus.rightMenus, maxRightMenus,
                        menus.rightMenus.size() - maxRightMenus);
                    for (Menu rightMenu : menuList) {
                        if (StringUtils.isNotEmpty(rightMenu.icon)) {
                            final Menu tempMenu = rightMenu;
                            Glide.with(WebFragment.this)
                                .load(rightMenu.icon)
                                .into(new SimpleTarget<GlideDrawable>() {
                                    @Override
                                    public void onResourceReady(GlideDrawable resource,
                                                                GlideAnimation<? super GlideDrawable> glideAnimation) {
                                        Action action = getActionBarLayout().addImageAction(
                                            MenuItem.MENU_ITEM_ID_INDEX + tempMenu.id, resource);
                                        action.setOnActionClickListener(getOnActionClickListener());
                                    }
                                });
                        } else if (StringUtils.isNotEmpty(rightMenu.name)) {
                            Action action = getActionBarLayout().addTextAction(
                                MenuItem.MENU_ITEM_ID_INDEX + rightMenu.id,
                                rightMenu.name);
                            action.setOnActionClickListener(getOnActionClickListener());
                        }
                    }
                } catch (Throwable throwable) {

                }
            }
        });
    }

    @Override
    public void setRefreshState(int state) {
        if (state == 1) {
            mWebViewParam.mNeedRefresh = true;
            mPtrFrameLayout.setMode(Mode.REFRESH);
        } else {
            mWebViewParam.mNeedRefresh = false;
            mPtrFrameLayout.setMode(Mode.NONE);
        }
    }
}
